package com.example.usermanagement.context;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.usermanagement.vo.UserInfoVO;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author yha
 * @ClassName
 * @description:TODO
 * @date 2024年09月10日
 * @version: 1.0.0
 */
public class JwtFilter implements Filter {

    private RedisTemplate redisTemplate;

    public JwtFilter(RedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }


    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        UserContext.removeUserInfoThreadLocal();
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        String accessToken = request.getHeader("token");



        if(!StrUtil.isEmpty(accessToken)){
            //进行解析
            Object userInfoVO = redisTemplate.opsForValue().get("TOKEN"+":"+accessToken);
            if(Objects.nonNull(userInfoVO)){
                UserInfoVO userInfoVO1 = JSONObject.parseObject(userInfoVO.toString(), UserInfoVO.class);
                UserContext.setUserInfoVOThreadLocal(userInfoVO1);
            }

        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
